import os

import xlrd
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud

'''
工具类
'''
class BaseHandle(object):

    def __init__(self):
        # 物流关键词词库：目前28个物流关键词
        self.logistics_list = ['京东', '新鲜', '包装', '物流', '很快', '快递', '收到', '速度', '送货', '推荐',
                               '小哥', '服务', '发货', '配送', '送到', '到货', '第二天', '冷链', '完好', '送货上门',
                               # 使用word2vec加的关键词 👇
                               '严谨','保障', '效率', '方便快捷', '客服', '省心', '快捷', '严实']

    def read_col_merge_file(self, url):
        '''读取合并列表comments列的值输出为txt'''
        excel = xlrd.open_workbook(url)  # 打开excel文件
        table = excel.sheet_by_index(0)  # 根据下标获取工作薄，这里获取第一个
        comments_list = table.col_values(1, start_rowx=1)  # 获取第一列的内容
        comments_str = '\n'.join(comments_list)  # 将数组转换成字符串,空行连接,模仿text文本
        return comments_str

    def words_fre_match(self, filename, lis):
        '''关键词批量匹配词频'''
        df = pd.read_excel(filename, sheet_name='Sheet1')#'高频词统计.xlsx'
        b1 = []
        b2 = []
        for i in range(len(df)):
            keyword = df.loc[i, 'keyword']
            if any(word if word == keyword else False for word in lis):  # 判断列表(list)内一个或多个元素是否与关键词相同
                a1 = df.loc[i, 'keyword']
                a2 = df.loc[i, 'fre']
                b1.append(a1)
                b2.append(a2)
            else:
                continue
        f1 = pd.DataFrame(columns=['关键词', '词频'])
        f1['关键词'] = b1
        f1['词频'] = b2
        f1.to_excel('物流关键词词频匹配表.xlsx')

    def wordcloud_by_wordcount(self, url):
        '''根据词汇及对应词频绘制词云图'''
        data = pd.read_excel(url, sheet_name='Sheet1') # 获得数据
        data_gr = data.groupby(by='关键词', as_index=False).agg({'词频': int}) # 拿数据
        dic = dict(zip(data_gr['关键词'], data_gr['词频'])) # 转化为字典形式
        # print(dic)

        # fit_word函数，接受字典类型，其他类型会报错
        wordcloud = WordCloud(font_path='simhei.ttf', background_color="white", width=4000, height=2000,
                              margin=10).fit_words(dic)
        plt.imshow(wordcloud)
        plt.axis("off") # 取消坐标轴
        plt.show() # 显示

    def get_file_abspath(self, filename):
        '''获取文件的根本路径，文件一般在\nlp_yinyu\下'''
        # 拼接路径
        path = os.path.join(os.path.dirname(os.getcwd()), filename)
        # 返回根本路径
        return os.path.abspath(path)


if __name__ == '__main__':
    base = BaseHandle()
    # comments_str = base.read_col_merge_file('语料库_京东_5000条评论.xlsx')
    # print(comments_str)

    # base.words_fre_match(os.path.abspath(os.getcwd() + '/01/高频词统计.xlsx'), base.logistics_list)

    base.wordcloud_by_wordcount(os.path.abspath(os.getcwd() + '/01/物流关键词词频匹配表.xlsx'))
    pass
